package com.imageim.yimirror.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseActivity;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.QRCodeBean;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.ui.btn.BtnCircleClose;
import com.imageim.yimirror.common.util.AppUtil;
import com.imageim.yimirror.common.util.CacheUtils;
import com.imageim.yimirror.common.util.PictureUtils;
import com.imageim.yimirror.common.util.TransitionUtils;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.net.NetPresenterImpl;
import com.imageim.yimirror.net.NetView;
import com.imageim.yimirror.ui.fragment.DressGuideFragment;
import com.imageim.yimirror.ui.fragment.IntelligenRecommendFragment;
import com.imageim.yimirror.ui.fragment.IntelligentAnalysisFragment;
import com.imageim.yimirror.ui.fragment.RecommendForYouFragment;
import com.imageim.yimirror.ui.fragment.TryClothPhotoFragment;
import com.imageim.yimirror.ui.fragment.tendency.ThemeItemFragment;
import com.martin.ads.omoshiroilib.util.BitmapUtils;

import java.text.MessageFormat;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Yuaihen.
 * on 2018/7/6
 * 主页--包含智能推荐/衣橱管理/穿衣指南/形象日记
 */
public class MainActivity extends BaseActivity implements NetView {

    @BindView(R.id.iv_userHead)
    ImageView mIvUserHead;
    @BindView(R.id.fl_container)
    FrameLayout mFlContainer;
    @BindView(R.id.btn_close)
    BtnCircleClose mBtnClose;
    @BindView(R.id.ll_personal_center)
    LinearLayout mLlPersonalCenter;
    @BindView(R.id.tv_version)
    TextView mTvVersion;
    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R.id.xTablayout)
    XTabLayout mXTablayout;
    private static final int RECOMMEND_FOR_YOU = 0;
    private static final int INTELLIGEN_ANALYSIS = 1;
    private static final int RECOMMEND = 2;
    private static final int DRESS_GUIDE = 3;
    private static final int IMAGE_PHOTO = 4;
    private static final int FRAGMENT_THEME_ITEMS = 6;
    private BaseFragment currentFragment;
    //当前是哪个Fragment
    private int currentPage = -1;
    private FragmentManager mFragmentManager;
    private FragmentTransaction mFragmentTransaction;
    private DressGuideFragment mDressGuideFragment;
    private TryClothPhotoFragment mImagePhotoFragment;
    private IntelligenRecommendFragment mRecommendFragment;
    private IntelligentAnalysisFragment mIntelligentAnalysisFragment;
    private ThemeItemFragment mThemeItemFragment; // 时尚趋势主题内部items
    private String mMiniProgramUrl;
    private String[] moduleNameArray = {"为您推荐", "智能分析", "智能推荐", "穿衣指南", "试穿留影"};
    private RecommendForYouFragment mRecommendForYouFragment;

    @Override
    protected void initBundle() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        mBtnClose.setCloseImage(R.drawable.ic_menu_exit, 300);
        mFragmentManager = getSupportFragmentManager();
    }


    @Override
    protected void initListener() {
        super.initListener();
        mBtnClose.setOnTimeOverListener(() -> {
            //debug时 不关闭页面
            finish();
        });

        for (int i = 0; i < moduleNameArray.length; i++) {
            //设置默认选中为您推荐
            if (i == 0) {
                mXTablayout.addTab(mXTablayout.newTab().setText(moduleNameArray[i]), true);
            } else {
                mXTablayout.addTab(mXTablayout.newTab().setText(moduleNameArray[i]));
            }
        }

        mXTablayout.addOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position == RECOMMEND_FOR_YOU) {
                    showRecommendForYouFragment();
                } else if (position == INTELLIGEN_ANALYSIS) {
                    showIntelligentAnalysisFragment();
                } else if (position == RECOMMEND) {
                    showRecommendFragment();
                } else if (position == DRESS_GUIDE) {
                    showDressGuideFragment();
                } else if (position == IMAGE_PHOTO) {
                    showImagePhotoFragment();
                }
            }

            @Override
            public void onTabUnselected(XTabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(XTabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected void initData() {
        mTvVersion.setText(MessageFormat.format("形象力时尚AI {0}版", AppUtil.getVersionName(mContext)));

        getQRCode();
        setUserHead();
        //默认显示为您推荐
        showRecommendForYouFragment();
    }


    /**
     * 获取二维码
     */
    private void getQRCode() {
        NetPresenterImpl netPresenter = new NetPresenterImpl(this);
        HashMap<String, String> map = new HashMap<>(4);
        map.put(Constants.PHOTO_NO, UserUtil.getPhotoNo());
        netPresenter.getObject(mContext, NetConstants.URL.GET_QRCODE, map, QRCodeBean.class, 0);
    }


    /**
     * 显示为您推荐Fragment
     */
    private void showRecommendForYouFragment() {
        if (currentPage == RECOMMEND_FOR_YOU) {
            return;
        }
        showVersion();
        showQrCode();

        if (mRecommendForYouFragment == null) {
            mRecommendForYouFragment = new RecommendForYouFragment();
        }
        addView(mRecommendForYouFragment, "mRecommendForYouFragment");
        currentPage = RECOMMEND_FOR_YOU;
    }


    /**
     * 显示智能分析
     */
    private void showIntelligentAnalysisFragment() {
        if (currentPage == INTELLIGEN_ANALYSIS) {
            return;
        }
        hideVersion();
        hideQrCode();
        if (mIntelligentAnalysisFragment == null) {
            mIntelligentAnalysisFragment = new IntelligentAnalysisFragment();
        }
        addView(mIntelligentAnalysisFragment, "mIntelligentAnalysisFragment");
        currentPage = INTELLIGEN_ANALYSIS;
    }


    /**
     * 显示智能推荐
     */
    public void showRecommendFragment() {
        if (currentPage == RECOMMEND) {
            return;
        }

        showVersion();
        showQrCode();

        //优先检查，fragment是否存在，避免重叠
        if (mRecommendFragment == null) {
            mRecommendFragment = new IntelligenRecommendFragment();
        }
        addView(mRecommendFragment, "mRecommendFragment");
        currentPage = RECOMMEND;
    }


    /**
     * 显示穿衣指南
     */
    private void showDressGuideFragment() {
        if (currentPage == DRESS_GUIDE) {
            return;
        }

        showQrCode();
        showVersion();

        if (mDressGuideFragment == null) {
            mDressGuideFragment = new DressGuideFragment();
        }
        addView(mDressGuideFragment, "dressGuideFragment");
        currentPage = DRESS_GUIDE;
    }

    /**
     * 显示试穿留影
     */
    private void showImagePhotoFragment() {
        if (currentPage == IMAGE_PHOTO) {
            return;
        }

        hideVersion();
        hideQrCode();

        if (mImagePhotoFragment == null) {
            mImagePhotoFragment = new TryClothPhotoFragment();
        }
        addView(mImagePhotoFragment, "imagePhotoFragment");
        currentPage = IMAGE_PHOTO;
    }


    /**
     * 跳转到个人中心
     */
    public void showPersonalCenterFragment() {
        Intent intent = new Intent(this, PersonalCenterActivity.class);
        TransitionUtils.startActivityWithSharedElements(this, intent, mIvUserHead, "sharedView");
    }


    /**
     * 设置用户头像
     */
    private void setUserHead() {
        if (!TextUtils.isEmpty(CacheUtils.getString(mContext, Constants.FACE_STR))) {
            String faceStr = CacheUtils.getString(mContext, Constants.FACE_STR);
            Bitmap bitmap = BitmapUtils.base64ToBitmap(faceStr);
            if (bitmap != null) {
                Bitmap faceBitmap = PictureUtils.createCircleImage(bitmap, bitmap.getWidth());
                mIvUserHead.setImageBitmap(faceBitmap);
            }
        }
    }


    @OnClick({R.id.iv_userHead, R.id.ll_personal_center})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_userHead:
                //跳转到个人中心
                showPersonalCenterFragment();
                break;
            case R.id.ll_personal_center:
                //跳转到个人中心
                showPersonalCenterFragment();
                break;
            default:
                break;

        }
    }


    /**
     * 设置Button选中状态并且改变选中时的字体大小
     * <p>
     * //     * @param index 需要选中的位置
     */
    //    private void setBtnSelect(int index) {
    //        for (int i = 0; i < mBtnArray.length; i++) {
    //            if (i == index) {
    //                mBtnArray[i].setSelected(true);
    //                mBtnArray[i].setTextSize(UIUtils.dip2px(mContext, 34));
    //                SoundUtil.playAsyc(mContext, R.raw.btn_home_menu_item, false);
    //            } else {
    //                mBtnArray[i].setSelected(false);
    //                mBtnArray[i].setTextSize(UIUtils.dip2px(mContext, 26));
    //            }
    //        }
    //    }
    @Override
    public void onLoadPre(int msgCode) {

    }

    @Override
    public void onLoadSuccess(Object result, int msgCode) {
        QRCodeBean bean = (QRCodeBean) result;
        if (bean != null) {
            mMiniProgramUrl = bean.getMiniProgramUrl();
            //        mIvQrCode.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(mMiniProgramUrl)) {
                GlideUtils.display(mIvQrCode, mMiniProgramUrl);
                UserUtil.setQrCodeUrl(mMiniProgramUrl);
            }
        }
    }

    @Override
    public void onLoadFail(int errorCode, String errorMsg, int msgCode) {
        toast(errorMsg + errorCode);
    }


    /**
     * 显示二维码
     */
    private void showQrCode() {
        if (!TextUtils.isEmpty(mMiniProgramUrl)) {
            mIvQrCode.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏二维码
     */
    private void hideQrCode() {
        mIvQrCode.setVisibility(View.GONE);
    }

    /**
     * 显示版本号
     */
    private void showVersion() {
        mTvVersion.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏版本号
     */
    private void hideVersion() {
        mTvVersion.setVisibility(View.GONE);
    }

    private void addView(BaseFragment fragment, String tag) {
        mFragmentTransaction = mFragmentManager.beginTransaction();
        //优先检查，fragment是否存在，避免重叠
        BaseFragment tempFragment = (BaseFragment) mFragmentManager.findFragmentByTag(tag);
        if (tempFragment != null) {
            fragment = tempFragment;
        }
        if (fragment.isAdded()) {
            addOrShowFragment(fragment, tag);
        } else {
            if (currentFragment != null && currentFragment.isAdded()) {
                mFragmentTransaction.hide(currentFragment).add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
            } else {
                mFragmentTransaction.add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
            }
            currentFragment = fragment;
        }
    }


    /**
     * 添加或者显示 fragment
     *
     * @param fragment
     */
    private void addOrShowFragment(BaseFragment fragment, String tag) {
        if (currentFragment == fragment || mFragmentManager == null || currentFragment == null) {
            return;
        }
        // 如果当前fragment未被添加，则添加到Fragment管理器中
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (!fragment.isAdded()) {
            transaction.hide(currentFragment).add(R.id.fl_container, fragment, tag).commitAllowingStateLoss();
        } else {
            transaction.hide(currentFragment).show(fragment).commitAllowingStateLoss();
        }

        currentFragment.setUserVisibleHint(false);
        currentFragment = fragment;
        currentFragment.setUserVisibleHint(true);
    }


    private long lastTouchEventTime;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (System.currentTimeMillis() - lastTouchEventTime > 1000 && mBtnClose.getCount() < 60) {
            lastTouchEventTime = System.currentTimeMillis();
            mBtnClose.restart(300);
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBtnClose != null) {
            mBtnClose.destory();
        }
    }

    @Override
    public void onEventMainThread(EventMessage event) {
        super.onEventMainThread(event);
        if (event.getCode() == EventCode.CODE_FINISH) {
            finish();
        }
    }
}
